<?php
session_start();
if(isset($_SESSION['admin_id'])) {
    include "../../include/dbFunctions.php";
    include("../../include/mail/mailFunctions.php");
    $id_array = $_POST['id'];
    $event_id = $_SESSION['eid'];
//empty check
    if (!isset($_POST['id'])) {
        $_SESSION['mes']="You must choose at least a volunteer";
    } else {
//update event status
        $query1 = "UPDATE event SET event_status='pending' WHERE event_id=$event_id";
        $result1 = executeQuery($query1);
//update volunteer status and send email
        $sent = 0;
        for($i=0;$i<count($id_array);$i++) {
            $id = $id_array[$i];
            $query4 = "SELECT volunteer_email from volunteer WHERE volunteer_id=$id";
            $result4 = executeSelectQuery($query4);
            //send email
            $now=date("Y-m-d H:i:s");
            //check if it's exist
            $querycheck = "SELECT * FROM trainer WHERE event_id = $event_id AND volunteer_id = $id";
            $check = executeSelectQuery($querycheck);
            if (!$check) {
                $query2 = "INSERT INTO trainer (event_id, volunteer_id, trainer_status) VALUES ('".$event_id."','".$id."','requested')";
                $result2 = executeQuery($query2);
                if ($result2!=0) {
                    //template
                    $template = templateRequest($event_id,$id,'requestVolunteer');
                    $to = $result4[0]['volunteer_email'];
                    $subject = $template['title'];
                    $message = $template['content'];
                    $headers = "From: hauyee.ng@ja.org" . "\r\n" .
                            "Reply-To: hauyee.ng@ja.org" . "\r\n" .
                            "X-Mailer: PHP/" . phpversion();
                    $sendresult = mail($to, $subject, $message, $headers);
                    if ($sendresult) {
                        $sent+=1;
                        $_SESSION['mes']="Your requests have been sent successfully to ".$sent." volunteers";
                    }else {
                        $_SESSION['mes']="Error in sending email. Please try again";
                    }
                } else {
                    $_SESSION['mes']="There is a database error. Please try again";
                }
            }
        }
    }
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    ?>
    <?php
}else {
    header("Location: ../include/login.html");
}
?>
